﻿using Mododor.DTO;
using Mododor.Ext;
using Mododor.JsonModels;
using Mododor.Models;
using Mododor.ViewInterfaces;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Mododor.ViewModels.CompanyInfoViewModels
{
    class ContractInfoViewModel : ViewInterface<ContractInfoModel>, INavigationAware
    {
        #region 合同类型右边隐藏菜单属性
        private bool rightDrawerHostOpen;

        public bool RightDrawerHostOpen
        {
            get { return rightDrawerHostOpen; }
            set { rightDrawerHostOpen = value; RaisePropertyChanged(); }
        }

        private ContractTypeModel contractTypeModel;

        public ContractTypeModel ContractTypeModel
        {
            get { return contractTypeModel; }
            set { contractTypeModel = value; RaisePropertyChanged(); }
        }
        #endregion
        private ContractTypeModel selectedContractTypeModel;

        public ContractTypeModel SelectedContractTypeModel
        {
            get { return selectedContractTypeModel; }
            set { selectedContractTypeModel = value; RaisePropertyChanged(); }
        }


        private ContractInfoModel contractInfoModel;

        public ContractInfoModel ContractInfoModel
        {
            get { return contractInfoModel; }
            set { contractInfoModel = value; RaisePropertyChanged(); }
        }

        private ClientInfoModel signClient;

        public ClientInfoModel SignClient
        {
            get { return signClient; }
            set { signClient = value; RaisePropertyChanged(); }
        }

        private ClientInfoModel billClient;

        public ClientInfoModel BillClient
        {
            get { return billClient; }
            set { billClient = value; RaisePropertyChanged(); }
        }

        private CompanyInfoModel companyInfo;

        public CompanyInfoModel CompanyInfo
        {
            get { return companyInfo; }
            set { companyInfo = value; }
        }

        //请求的旧多对多关系
        public long ClientSignPersonOld { get; set; }
        public long ClientBillPersonOld { get; set; }

        public DelegateCommand GetNumCommand { get; set; }
        public DelegateCommand CompanySelectionChangedCommand { get; set; }
        public DelegateCommand ContractTypeAddViewCommand { get; set; }
        public DelegateCommand ContractTypeClearCommand { get; set; }
        public DelegateCommand ContractTypeSaveCommand { get; set; }
        public DelegateCommand ContractTypeDeleteCommand { get; set; }
        public DelegateCommand DataGridSelectionChangedCommand { get; set; }
        public ContractInfoViewModel(IDialogService dialog, HttpHelper http) : base(dialog, http)
        {
            ContractInfoModel = new ContractInfoModel();
            ContractTypeModel = new ContractTypeModel();
            CompanySelectionChangedCommand = new DelegateCommand(async () =>
            {
                if (CompanyInfo is null)
                {
                    return;
                }
                await GetClientList(CompanyInfo.Id);
            });

            GetNumCommand = new DelegateCommand(async () =>
            {
                string json=await _httpHelper.GetJson(ExtUrl.ContractAutoGetIdUrl);
                long id =long.Parse( JsonConvert.DeserializeObject<ContractInfoAutoGetIdJsonModel.Rootobject>(json).res);
                ContractInfoModel.IdContractInput = id;
            });

            SaveDataCommand = new DelegateCommand(async () =>
            {
                try
                {
                    IsOpen = true;
                    //请求参数赋值
                    ContractInfoRequestDTO contractDTO = new ContractInfoRequestDTO()
                    {
                        ClientBillPersonOld = ClientBillPersonOld,
                        ClientSignPersonOld = ClientSignPersonOld,
                        ContractCompanyID = CompanyInfo.Id,
                        ContractTypeid = SelectedContractTypeModel.IdContractType,
                        ClientBillPerson = BillClient.idClient,
                        ClientSignPerson = SignClient.idClient,
                        ContractActive = ContractInfoModel.ContractActive,
                        ContractContent = ContractInfoModel.ContractContent,
                        ContractEndDate = ContractInfoModel.ContractEndDate,
                        ContractStartDate = ContractInfoModel.ContractStartDate,
                        ContractHours = (ContractInfoModel.ContractEndDate - ContractInfoModel.ContractStartDate).Days*24,
                        ContractName = ContractInfoModel.ContractName,
                        Id = ContractInfoModel.IdContract,
                        idContract = ContractInfoModel.IdContractInput,
                    };
                    string json = JsonConvert.SerializeObject(contractDTO);
                    string jsonRes = await _httpHelper.PostJson(ExtUrl.ContractOperationUrl, json);
                    JustHaveStausAndMsgInfoJsonModel.Rootobject root = JsonConvert.DeserializeObject<JustHaveStausAndMsgInfoJsonModel.Rootobject>(jsonRes);

                    await InitialViewData();
                    IsOpen = false;
                    SnackBarMessage = root.msg;
                }
                catch (Exception ex)
                {
                    SnackBarMessage = ex.Message;
                }
                finally
                {
                    IsOpen = false;
                    await SnackBarWaiting();
                }

            });

            MarkingDeleteCommand = new DelegateCommand(async () =>
            {
                try
                {
                    IsOpen = true;
                    string json = await _httpHelper.GetJson($"{ExtUrl.ContractMarkingDeleteUrl}?contractId={ContractInfoModel.IdContract}");
                    JustHaveStausAndMsgInfoJsonModel.Rootobject root = JsonConvert.DeserializeObject<JustHaveStausAndMsgInfoJsonModel.Rootobject>(json);
                    IsOpen = false;
                    SnackBarMessage = root.msg;
                }
                catch (Exception ex)
                {
                    SnackBarMessage = ex.Message;
                }
                await SnackBarWaiting();
                await InitialViewData();
            });

            ClearDataCommand = new DelegateCommand(() =>
            {
                ContractInfoModel = new ContractInfoModel();
            });

            DataGridSelectionChangedCommand = new DelegateCommand(() =>
            {
                if (ContractInfoModel is null)
                {
                    return;
                }
                BillClient = ClientList.ToList().Find(x => x.idClient == ContractInfoModel.BillClient.idClient);
                SignClient = ClientList.ToList().Find(x => x.idClient == ContractInfoModel.SignClient.idClient);
                SelectedContractTypeModel = ContractTypeModelList.ToList().Find(x => x.IdContractType == ContractInfoModel.ContractTypeModel.IdContractType);
                ClientBillPersonOld = ContractInfoModel.BillClient.idClient;
                ClientSignPersonOld = ContractInfoModel.SignClient.idClient;
            });

            ContractTypeAddViewCommand = new DelegateCommand(async () =>
            {
                RightDrawerHostOpen = true;
                await GetContractTypeList();
            });
            ContractTypeClearCommand = new DelegateCommand(() =>
            {
                ContractTypeModel = new ContractTypeModel();
            });
            ContractTypeSaveCommand = new DelegateCommand(async () =>
            {
                try
                {
                    string json = JsonConvert.SerializeObject(ContractTypeModel);
                    string jsonRes = await _httpHelper.PostJson(ExtUrl.ContractTypeOperationUrl, json);
                    JustHaveStausAndMsgInfoJsonModel.Rootobject root = JsonConvert.DeserializeObject<JustHaveStausAndMsgInfoJsonModel.Rootobject>(jsonRes);
                    SnackBarMessage = root.msg;
                }
                catch (Exception ex)
                {
                    SnackBarMessage = ex.Message;
                }
                finally
                {
                    await GetContractTypeList();
                    await SnackBarWaiting();
                }
            });
            ContractTypeDeleteCommand = new DelegateCommand(async () =>
            {
                try
                {
                    string json = JsonConvert.SerializeObject(ContractTypeModel);
                    string jsonRes = await _httpHelper.GetJson($"{ExtUrl.ContractTypeMarkingDeleteUrl}?contractTypeId={ContractTypeModel.IdContractType}");
                    JustHaveStausAndMsgInfoJsonModel.Rootobject root = JsonConvert.DeserializeObject<JustHaveStausAndMsgInfoJsonModel.Rootobject>(jsonRes);
                    SnackBarMessage = root.msg;

                }
                catch (Exception ex)
                {
                    SnackBarMessage = ex.Message;
                }
                finally
                {
                    await GetContractTypeList();
                    await SnackBarWaiting();
                }
            });
        }

        protected override async Task GetCompanyList()
        {
            await base.GetCompanyList();
        }
        protected override async Task GetClientList(long idCompany)
        {
            IsOpen = true;
            await GetDataGridList(idCompany);
            await base.GetClientList(idCompany);
            IsOpen = false;
            await SnackBarWaiting();
        }
        protected override async Task GetContractTypeList()
        {
            await base.GetContractTypeList();
        }
        protected override Task SnackBarWaiting()
        {
            return base.SnackBarWaiting();
        }
        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            await InitialViewData();
        }

        async Task InitialViewData()
        {
            IsOpen = true;
            ContractInfoModel = new ContractInfoModel();
            DataStatsValueList.Clear();
            await GetCompanyList();
            await GetContractTypeList();
            IsOpen = false;
        }

        async Task GetDataGridList(long idCompany)
        {
            DataStatsValueList.Clear();
            string json = await _httpHelper.GetJson($"{ExtUrl.ContractSearchAllUrl}?idCompany={idCompany}");
            try
            {
                ContractInfoJsonSearchModel.Rootobject root = JsonConvert.DeserializeObject<ContractInfoJsonSearchModel.Rootobject>(json);
                foreach (var companyItem in root.res)
                {
                    string x = "", y = "";//签订人和账单人
                    long x1 = 0, y1 = 0;//签订人和账单人
                    foreach (var contractItem in companyItem.contracts)
                    {
                        if (contractItem.clientModels.Length > 1)
                        {
                            x = contractItem.clientModels[0].clientName;
                            x1 = contractItem.clientModels[0].idClient;
                            y1 = contractItem.clientModels[1].idClient;
                            y = contractItem.clientModels[1].clientName;
                        }
                        else if (contractItem.clientModels.Length == 1)
                        {
                            x = contractItem.clientModels[0].clientName;
                            x1 = contractItem.clientModels[0].idClient;
                            y1 = contractItem.clientModels[0].idClient;
                            y = contractItem.clientModels[0].clientName;
                        }


                        DataStatsValueList.Add(new ContractInfoModel()
                        {
                            IdCompany = idCompany,
                            CompanyName = companyItem.companyName,
                            ContractName = contractItem.contractName,
                            ContractContent = contractItem.contractContent,
                            IdContract = contractItem.idContract,
                            IdContractInput = contractItem.idContractInput,
                            ContractActive = contractItem.ContractActive,
                            ContractEndDate = contractItem.contractEndDate,
                            ContractStartDate = contractItem.contractStartDate,
                            ContractTypeModel = new ContractTypeModel()
                            {
                                ContractTypeDescription = contractItem.contractType.contractTypeDescription,
                                ContractTypeName = contractItem.contractType.contractTypeName,
                                IdContractType = contractItem.contractType.idContractType,
                            },
                            BillClient = new ClientInfoModel()
                            {
                                idClient = x1,
                                ClientNameCh = x
                            },
                            SignClient = new ClientInfoModel()
                            {
                                idClient = y1,
                                ClientNameCh = y
                            },
                        });
                    }
                }

                SnackBarMessage = root.msg;
            }
            catch (Exception ex)
            {
                SnackBarMessage = ex.Message;
            }

        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
    }
}